package com.bdq.search.domain.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.bdq.search.domain.model.dto.req.SearchHistoryAddReqDTO;
import com.bdq.search.domain.model.dto.req.SearchHistoryDeleteReqDTO;
import com.bdq.search.domain.service.SearchDomainService;
import com.bdq.search.infrastructure.persistence.mysql.pojo.SearchHistory;
import com.bdq.search.infrastructure.persistence.mysql.service.SearchHistoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author malei
 * @date 2024-05-26 16:45
 */
@Service
public class SearchDomainServiceImpl implements SearchDomainService {

    @Resource
    private SearchHistoryService searchHistoryService;

    @Override
    public Boolean deleteSearchHistory(SearchHistoryDeleteReqDTO reqDTO) {
        return searchHistoryService.deleteSearchHistory(reqDTO.getUserId(), reqDTO.getKeyword());
    }

    @Override
    public Boolean saveSearchHistory(SearchHistoryAddReqDTO reqDTO) {
        // 1 保存搜索历史
        SearchHistory searchHistory = new SearchHistory();
        searchHistory.setUserId(reqDTO.getUserId());
        searchHistory.setContent(reqDTO.getKeyword());
        searchHistoryService.save(searchHistory);
        // 2 删除搜索历史
        List<SearchHistory> searchHistoryList = searchHistoryService.listByUserId(reqDTO.getUserId());
        if (searchHistoryList.size() > 15) {
            List<SearchHistory> deleteList = searchHistoryList.subList(15, searchHistoryList.size());
            List<Long> deleteIds = deleteList.stream().map(SearchHistory::getId).collect(Collectors.toList());
            searchHistoryService.deleteBatchByIds(deleteIds);
        }
        return true;
    }
}
